<template>
  <div v-if="editOpen" style="width: 100%;">
    <t-table rowKey="id" :data="data" :columns="columns" :selected-row-keys="selectedRowKeys"
      @select-change="(val) => { selectedRowKeys = val }">
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #op="{ row, rowIndex }">
        <file-upload action="/prod-api/file/sysAttMain/kpzhUploadImg"
          @change="(value, context) => { onUploadChange(value, context, row) }" :status="row.imageStatus"
          v-model="row.sysAttMainVo.sysAttMainIds" :sizeLimitRange="sizeLimitRange"
          :fileList.sync="row.sysAttMainEntities" :max="1" :multiple="false" accept="image/*" theme="image" tips="">
          <t-button variant="outline">
            <t-icon name="cloud-upload" slot="icon" />
            点击上传
          </t-button>
          <div slot="tips" v-if="row.imageStatus === 'error'">不能为空</div>
        </file-upload>
      </template>
      <!-- <template #op="{ row, rowIndex }">
        <file-upload :status="row.imageStatus" accept="image/*" v-model="row.sysAttMainVo.sysAttMainIds"
          :sizeLimitRange="sizeLimitRange" :fileList.sync="row.sysAttMainEntities" :max="1" :multiple="false"
          tips="限制图片">
          <t-button variant="outline">
            <t-icon name="cloud-upload" slot="icon" />
            点击上传
          </t-button>
          <div slot="tips" v-if="row.imageStatus === 'error'">不能为空</div>
        </file-upload>
      </template> -->
      <template #state="{ row }">
        <t-textarea @change="() => { if (row.state !== '') { row.stateStatus = 'default' } }" :status="row.stateStatus"
          clearable :autosize="{ minRows: 3 }" :maxlength="50" v-model="row.state">
          <div slot="tips" v-if="row.stateStatus === 'error'">不能为空</div>
        </t-textarea>
      </template>
    </t-table>
    <div style="margin-top: 10px" class="btn-group-inline">
      <t-button :disabled="this.data.length >= 10" @click="addData">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else style="width: 100%;">
    <t-table rowKey="id" :data="data" :columns="columns2">
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>

      <template #op="{ row }">

        <div v-for="(item, index) in row.sysAttMainEntities" :key="index">
          <a class="t-button-link" target="_blank" :href="item.fullFilePath">
            {{ item.fileName }}
          </a>
        </div>

      </template>
    </t-table>
  </div>
</template>

<script lang="jsx">
import FileUpload from "@/components/FileUpload/index.vue"


export default {
  name: "base-image",
  components: {
    FileUpload
  },
  props: {
    objId: [String, Number],
    value: Array,
    editOpen: {
      type: Boolean,
      default: false
    },
    sizeLimitRange: {
      type: Array,
      default: () => [0, 1048576 * 2]
    },
  },
  data () {
    return {
      data2: [],
      data: [],
      selectedRowKeys: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64
        },
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 80
        },
        {
          colKey: "op",
          title: "图片(大小不能超过2M，图片不能过宽过长，一张word页面可以显示即可)",
          align: "center",
          // title: (h, {colIndex}) => <div><span style="color: red;margin-right: 3px;">*</span>图片</div>,
        },
        {
          colKey: "state",
          title: "简要说明",
          align: "center",
          // title: (h, {colIndex}) => <div><span style="color: red;margin-right: 3px;">*</span>说明</div>,
        },
      ],
      columns2: [
        {
          colKey: 'index',
          title: "序号",
          align: "center",
          width: 80
        },
        {
          colKey: "op",
          title: "附件",
          align: "center",
        },
        {
          colKey: "state",
          title: "说明",
          align: "center",
        },
      ]
    }
  },
  watch: {
    data: {
      handler (val, old) {
        const newData = this.data.map((d, index) => ({ ...d, sort: index + 1 }))
        this.$emit("input", newData);
      },
      immediate: true,
      deep: true,
    },
    value: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val && val.length > 0) {
          const newArr = val.map(data => ({
            ...data,
            initType: 'init',
            sysAttMainVo: {
              sysAttMainIds: data?.sysAttMainVo?.sysAttMainIds || []
            },
            sysAttMainEntities: data.sysAttMainEntities?.map(val => ({
              ...val,
              name: val.fileName,
              url: val.fullFilePath,
              fullFilePath: val.fullFilePath,
              id: val.id,
              filePath: val.filePath
            })),
          }))
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
          }
        }
      }
    },

  },
  async created () {

  },
  methods: {

    checkData () {
      const title = "嘉奖情况"
      // 非空判断
      const isValidate = this.data.every((val, index) => {
        if ((val.sysAttMainVo?.sysAttMainIds && val.sysAttMainVo?.sysAttMainIds?.length <= 0) || !val.sysAttMainVo?.sysAttMainIds) {
          this.$set(this.data[index], 'imageStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"附件"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'imageStatus', 'default')

        if (!val.state) {
          this.$set(this.data[index], 'stateStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"简要"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'stateStatus', 'default')
        return true;
      })
      return isValidate;
    },
    addData () {
      this.data.push({
        id: Date.parse(new Date()),
        baseId: this.objId,
        sysAttMainVo: {
          sysAttMainIds: [],
        },
        // sysAttMainEntities: [],
        state: '',
      })
    },
    upData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray (arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    updateFileList (val, rowIndex) {
      this.$set(this.data[rowIndex], "sysAttMainEntities", val[0]);
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .t-upload__card {
  justify-content: center;
}

/deep/ .t-upload__single-display-text {
  justify-content: center;
}

/deep/ .t-upload__card-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.tdesign-demo-image-viewer__ui-image {
  width: 160px;
  height: 160px;
  display: inline-flex;
  position: relative;
  justify-content: center;
  align-items: center;
  border-radius: var(--td-radius-small);
  overflow: hidden;
}

.tdesign-demo-image-viewer__ui-image--hover {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: var(--td-text-color-anti);
  line-height: 22px;
  transition: 0.2s;
  z-index: 1000;
}

.tdesign-demo-image-viewer__ui-image:hover .tdesign-demo-image-viewer__ui-image--hover {
  opacity: 1;
  cursor: pointer;
}

.tdesign-demo-image-viewer__ui-image--img {
  width: 160px;
  height: 160px;
  max-width: 100%;
  max-height: 100%;
  cursor: pointer;
  position: absolute;
}

.tdesign-demo-image-viewer__ui-image--footer {
  padding: 0 16px;
  height: 56px;
  width: 100%;
  line-height: 56px;
  font-size: 16px;
  position: absolute;
  bottom: 0;
  color: var(--td-text-color-anti);
  background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0) 100%);
  display: flex;
  box-sizing: border-box;
}

.tdesign-demo-image-viewer__ui-image--title {
  flex: 1;
}

.tdesign-demo-popup__reference {
  margin-left: 16px;
}

.tdesign-demo-image-viewer__ui-image--icons .tdesign-demo-icon {
  cursor: pointer;
}

.tdesign-demo-image-viewer__base {
  width: 160px;
  height: 160px;
  margin: 10px;
  border: 4px solid var(--td-bg-color-secondarycontainer);
  border-radius: var(--td-radius-medium);
}
</style>
